package com.hschinese.pronunciation.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wo on 2015/11/11.
 */
public class SimpleRecordUtil {
    private Context mContext = null;
    private MediaRecorder mMediaRecorder;
    private File recAudioFile;
    private static MediaPlayer mMediaPlayer;
    public static final String recPath = Constant.rootDir + Constant.appDir + Constant.tempDir + "temp.amr";
    private PlayCompleteListener mListener;
    private Timer timer;
    private TimerTask task;
    private int volume;
    private VolumeListener mVolumeListener = null;

    private static SimpleRecordUtil mInstance = null;
    private SimpleRecordUtil(Context ctx) {
        mContext = ctx;
        recAudioFile = new File(recPath);
        if (!recAudioFile.exists()) {
            try {
                recAudioFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static SimpleRecordUtil getInstance(Context ctx) {
        synchronized (SimpleRecordUtil.class) {
            if (mInstance == null) {
                mInstance = new SimpleRecordUtil(ctx);
            }
            return mInstance;
        }
    }

    public boolean startRecorder() {
        mMediaRecorder = new MediaRecorder();
        if (recAudioFile.exists()) {
            recAudioFile.delete();
        }
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mMediaRecorder.setOutputFile(recAudioFile.getAbsolutePath());

            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
            if (mMediaRecorder != null) {
                mMediaRecorder.release();
                mMediaRecorder = null;
            }
            return false;
        }
        getVolume();
        return true;
    }

    public void stopRecorder(){
        if (timer != null) {
            timer.cancel();
        }
        if (mMediaRecorder != null) {
            try {
                mMediaRecorder.stop();
                mMediaRecorder.release();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mMediaRecorder = null;
            }
        }
    }

    public int playMicFile(File file){
        int duration = 1200;
        try {
            if (file != null && file.exists() && file.length() > 0) {
                Uri uri = Uri.fromFile(file);
                mMediaPlayer = MediaPlayer.create(mContext, uri);
                mMediaPlayer.start();
                duration = mMediaPlayer.getDuration();
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    public void onCompletion(MediaPlayer mp) {
                        Logger.e("play Finish");
                        if (mListener != null)
                            mListener.playComplete();
                        stopPlayer();
                    }
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            Logger.e("xionghy - playMicFile - duration: " + duration);
            return duration;
        }
    }

    public void stopPlayer(){
        if(mMediaPlayer != null){
            try {
                mMediaPlayer.stop();
                mMediaPlayer.release();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public void setPlayCompleteListener(PlayCompleteListener listener) { mListener = listener; }

    public void setVolumeListener(VolumeListener listener) { mVolumeListener = listener; }

    private Handler mHandler =new Handler(){
        public void handleMessage(Message msg){
            if (mVolumeListener != null) {
                mVolumeListener.updateVolume(msg.arg1);
            }
            getVolume();
        }
    };

    private  void getVolume(){
        timer=new Timer();
        task=new TimerTask(){
            @Override
            public void run() {
                if (mMediaRecorder != null) {
                    volume = mMediaRecorder.getMaxAmplitude();
                    Message message = mHandler.obtainMessage();
                    message.arg1 = (int) (volume / 1000);
                    mHandler.sendMessage(message);
                }
            }
        };
        timer.schedule(task, 200);
    }
}
